<template>
<!--用户管理-->
  <div class="user-list">
    <ToolBar>
      <el-button type="primary" icon="el-icon-plus" size="small" @click="add">添加新用户</el-button>
      <div style="float: right">
        <el-input placeholder="请输入内容" v-model="fieldVal" size="small" style="width: 340px" clearable>
          <el-select v-model="field" slot="prepend" placeholder="请选择" style="width:100px">
            <el-option label="用户名" value="username"></el-option>
            <el-option label="手机" value="phone"></el-option>
            <el-option label="邮箱" value="email"></el-option>
          </el-select>
          <el-button @click="search" slot="append" type="primary" icon="el-icon-search"></el-button>
        </el-input>
      </div>
    </ToolBar>
    <el-table v-loading="loading" :data='users' border ref="table" style="width: 100%">
      <el-table-column prop="username" width="200" align="center" label="用户名">
      </el-table-column>
      <el-table-column prop="gender" width="80" align="center" label="性别">
        <div slot-scope='{row}' style="width: 100%;text-align: center" class="genderBtn">
          <el-button size="small" circle type="" :style="row.gender=='f'?'backgroundColor:rgba(245,108,108,.2);color:#f56c6c':'backgroundColor:rgb(238, 250, 255);color:#3C8DBC'">{{row.gender=='f'?'女':'男'}}</el-button>
        </div>
      </el-table-column>
      <el-table-column prop="phone" width="250" align="center" label="手机">
      </el-table-column>
      <el-table-column prop="email" width="250" align="center" label="邮箱">
      </el-table-column>
      <el-table-column label="操作" align="center" :render-header="tableAction">
        <template slot-scope='{row}'>
          <el-popover placement="top-start" width="50" trigger="hover" content="编辑" class="btnPop">
              <el-button slot="reference" @click="edit(row.id)" type="primary" icon="el-icon-edit" size="small" circle style="backgroundColor:rgb(238, 250, 255);color:#3C8DBC"></el-button>
          </el-popover>
          <el-popover placement="top-start" width="50" trigger="hover" content="删除" class="btnPop">
              <el-button slot="reference" @click="del(row.id)" type="danger" icon="el-icon-delete" circle size="small" style="backgroundColor:rgb(255,255,255);color:#f56c6c"></el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="prev, pager, next ,sizes" :total="total" :page-sizes='[5,10,20]' :page-size='pageSize' :current-page.sync='currentPage' @current-change='currentChange' @size-change='sizeChange'></el-pagination>
    <!--编辑用户-->
    <el-dialog title="编辑用户" :visible="dialogFormVisible" width="40%" :show-close="false">
      <el-form :model="editForm" status-icon label-position="right" ref="editForm" :rules="rules">
        <el-form-item label="用户名" label-width="70px" prop="username">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="70px" prop="phone">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="70px" prop="gender">
          <el-select v-model="editForm.gender">
            <el-option label="女" value="f"></el-option>
            <el-option label="男" value="m"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('editForm')">取 消</el-button>
        <el-button type="primary" @click="submit('editForm',editForm.id)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ToolBar from '@/components/ToolBar.vue';
import HelpHint from '@/components/HelpHint.vue';

export default {
  data() {
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('电话不能为空'));
      }
      setTimeout(() => {
        if (!/^1\d{10}$/.test(value)) {
          callback(new Error('请输入11位格式正确的电话号码'));
        } else {
          callback();
        }
      }, 500);
    };
    let checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'));
      }
      setTimeout(() => {
        if (!/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(value)) {
          callback(new Error('请输入格式正确的邮箱'));
        } else {
          callback();
        }
      }, 500);
    };
    return {
      field: '',
      fieldVal: '',
      users: [],
      pageSize: 5,
      currentPage: 1,
      total: 0,
      loading: false,
      dialogFormVisible: false,
      editForm: {
        id: '',
        username: '',
        phone: '',
        email: '',
        gender: 'm',
      },
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        gender: [
          { message: '请选择性别', trigger: 'blur' }
        ],
        phone: [
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
    }
  },
  created() {
    this.getUsers();
  },
  methods: {
    getUsers() {
      this.loading = true;
      this.axios.get('/users', {
        params: {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          field: this.field,
          fieldVal: this.fieldVal,
        }
      }).then((ret) => {
        this.loading = false;
        const { data } = ret.data;
        this.total = data.total;
        this.users = data.rows;
      }).catch(() => { })
    },
    currentChange() {
      this.getUsers();
    },
    sizeChange(size) {
      this.pageSize = size;
      this.getUsers();
    },
    search() {
      this.getUsers();
    },
    add() {
      this.$router.push({ name: 'userAdd' })
    },
    edit(id) {
      this.dialogFormVisible = true;
      this.axios.get('/users/' + id).then((ret) => {
        let { data } = ret.data;
        this.editForm.username = data.username;
        this.editForm.phone = data.phone;
        this.editForm.email = data.email;
        this.editForm.gender = data.gender;
        this.editForm.id = data.id;
      }).catch(() => { })
    },
    del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.axios.delete('/users/del/' + id).then(() => {
          this.getUsers();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => { })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    tableAction() {
      return this.$createElement('HelpHint', {
        props: {
          content: '  编辑用户 / 删除或恢复用户'
        }
      }, '操作');
    },
    submit(form, id) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.axios.put('/users/edit/' + id, this.editForm).then(() => {
            this.getUsers();
            this.$refs[form].resetFields();
            this.dialogFormVisible = false;
            this.$message({
              message: '编辑成功',
              type: 'success'
            });
          }).catch(() => { })
        } else {
          this.$message.error('错了哦，请正确填写表单内容');
        }
      });
    },
    cancel(form) {
      this.$refs[form].resetFields();
      this.dialogFormVisible = false;
    },
  },
  components: {
    ToolBar, HelpHint
  }
}
</script>
<style lang="less">
.el-select {
  display: block;
}
.el-popover--plain{
  padding: 5px;
}
.el-popover{
  min-width: 0;
  text-align: center;
  box-shadow:0 2px 12px 0 rgba(0,0,0,0);
}
.el-table .cell .btnPop{
  margin: 10px;
}
.genderBtn .el-button--small.is-circle{
  border: none;
}
.el-tree-node {
    .el-tree-node__content {
        height: 50px;
        line-height: 50px;
    }
}
</style>
